
class SearchController < ApplicationController

  def suggest
     q = params[:q]
     @products = if q.strip.present?
                   Product.where("title LIKE ?", "%#{q}%").limit(10).order('updated_at DESC')
                 else
                   []
                 end
     render json: @products.to_json
  end

  def query
    params[:q] ||= ""

    search_modules = [Product]
    search_params = {
      settings: {
        analysis: {
          analyzer: {
            ik: {
              tokenizer: "ik_smart"
            }
          }
        }
      },
      sort: [
        {price: {order: "desc"}},
        {sales: { order: 'desc'}}
      ],
      query: {
        bool: {
          should: [
            { match: {title: params[:q]} },
            { match: {desc: params[:q]} }
          ],
          filter: [
            { term: { brand_id: 1} }
          ]
        }
      },
      #query: {
        #multi_match: {
          #query: params[:q],
          #fields: %w(title desc price)
        #}
      #},
      #filter: {
        #term: { price: 1}
      #},
      highlight: {
        pre_tags: ["[h]"],
        post_tags: ["[/h]"],
        fields: { title: {}, desc: {} }
      }
    }
    @result = Product.search(search_params).records.where(brand_id: 1).paginate(per_page: 1, page: 1)
    render json: @result
  end

end
